package Dao.imp;

import entity.User;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import utils.SqlSessionFactoryUtils;

import java.util.List;

public class UserDao implements UserMapper {

    private SqlSessionFactory sqlSessionFactory;

    public UserDao() {
        sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    }

    @Override
    public int addUser(User user) {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()){
            result = session.insert("addUser", user);
            session.commit();
        }
        return result;
    }

    @Override
    public int deleteUser(int uid) {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()){
            result = session.delete("deleteUser", uid);
            session.commit();
        }
        return result;
    }

    @Override
    public int updateUser(User user) {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()){
            result = session.update("updateUser", user);
            session.commit();
        }
        return result;
    }

    @Override
    public User queryUser(int uid) {
        User user = null;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            user = session.selectOne("queryUser", uid);
        }
        return user;
    }

    @Override
    public int queryUserUid(String username) {
        int uid = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            uid = session.selectOne("queryUserUid", username);
        } catch (NullPointerException e) {
            return -1;
        }
        return uid;
    }

    @Override
    public List<User> queryAllUser() {
        List<User> list = null;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            list = session.selectList("queryAllUser");
        }
        return list;
    }

    @Override
    public int getUserCount() {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            result = session.selectOne("getUserCount");
        }
        return result;
    }
}
